package com.jbp.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.domin.LuckReq2;
import com.jbp.model.*;
import com.jbp.model.Pool;
import com.jbp.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 抽奖，补礼物定时任务
 */
@Component
@Configuration
public class ProtectGiftsJob {

    @Autowired
    private ProtectGiftsService protectGiftsService;

    @Autowired
    private LotteryRecordService lotteryRecordService;

    @Autowired
    private UserDailyLuckRecordService userDailyLuckRecordService;

    @Autowired
    private UserPacksackService userPacksackService;

    @Autowired
    private PoolGiftConfigService poolGiftConfigService;

    @Autowired
    private GiftLotService giftLotService;

    @Autowired
    private GiftService giftService;

    @Autowired
    private ProtectGiftUserService  protectGiftUserService;

    @Autowired
    private PoolXUserService poolXUserService;

    @Autowired
    private PoolService poolService;

    @Autowired
    private PrizePatchService  prizePatchService;

    @Autowired
    private UserService userService;

    @Autowired
    private DevicePoolService devicePoolService;


    @Scheduled(cron = "0 59 23 * * *")
//    @Scheduled(fixedDelay = 1000*60*3)
    @Transactional
    public void checkProtectGifts(){
        Integer price = 20;
        List<UserDailyLuckRecord> userDailyLuckRecordList = userDailyLuckRecordService.getRecordDate(price);
        if (userDailyLuckRecordList != null && userDailyLuckRecordList.size() > 0) {
            for (UserDailyLuckRecord record : userDailyLuckRecordList) {
                HashMap<String, BigDecimal> map = userDailyLuckRecordService.getLuckByType(record.getUserId(), price);
                Integer pay = map.get("pay").intValue();
                if (pay !=null && pay.intValue()>=200000 && pay.intValue()<=200200){
                    Integer income = map.get("income").intValue();
                    int totalPay = pay;
                    int totalIncome = income;
                    //抽奖后爆率
                    if (!checkRate105(totalPay, totalIncome)) {
                        boolean flag = false;//是否需要保存用户处理过
                        /*Pool pool;
                        DevicePool devicePool = null;
                        //取设备池 判断是否在设备池中,设备池优先级最高
                        User user = userService.getById(record.getUserId());
                        if (null != user && null != user.getDevice() && !"".equals(user.getDevice())) {
                            devicePool = devicePoolService.getOne(new QueryWrapper<DevicePool>().eq("device_name", user.getDevice()));
                        }
                        //取黑白池
                        PoolXUser poolXUser = poolXUserService.getByPrice(record.getUserId(), price);
                        if (devicePool != null){
                            String poolName = devicePool.getPoolName();//设备池名称
                            //获取用户在该奖池的总投入
                            BigDecimal payDailyLuckRecord = userDailyLuckRecordService.getAllPayByType(record.getUserId(), price);
                            //获取门槛大于用户投入的第一个奖池
                            QueryWrapper<Pool> wrapper = new QueryWrapper<>();
                            wrapper.like("name", poolName);
                            wrapper.eq("type", 0);
                            wrapper.eq("state", 1);
                            wrapper.eq("price", price);
                            wrapper.le("start", payDailyLuckRecord);
                            wrapper.orderByDesc("inx");
                            wrapper.last("limit 1");
                            pool = poolService.getOne(wrapper);
                        }else if (poolXUser != null) {
                            pool = poolService.getById(poolXUser.getPoolId());
                        } else {
                            LuckReq2 luckReq =  new LuckReq2();
                            luckReq.setUserId(record.getUserId());
                            luckReq.setPrice(price);
                            pool = poolService.getPool(luckReq);
                        }
                        if (pool == null) {
                            return;
                        }
                        int poolId = pool.getId();*/
                        /*List<GiftLot> lots = giftLotService.list(new QueryWrapper<GiftLot>()
                                .eq("pool_type", price+"")
                        );

                        List<Gift> configGifts = lots.stream().map(GiftLot::getGiftId).distinct()
                                .map(giftId->giftService.getById(giftId))
                                .filter(gift -> gift.getCoin()>500 || gift.getType()==1).collect(Collectors.toList());*/
                        QueryWrapper<Gift> queryWrapper = new QueryWrapper<>();
                        queryWrapper.inSql("id","select gift_id from gift_lot WHERE pool_type = '"+20+"'");
                        queryWrapper.gt("coin",500);
                        queryWrapper.orderByDesc("coin");
                        List<Gift> configGifts = giftService.list(queryWrapper);


                        /*List<Gift> configGifts = poolGiftConfigService.getGiftsByPoolId(poolId)
                                .stream()
                                .filter(gift -> gift.getCoin() > 500 || gift.getType()==1)
                                .collect(Collectors.toList());*/
                        if (configGifts != null && configGifts.size() > 0) {
//                            Collections.reverse(configGifts);
                            //取一个新礼物  替换后  用户超过105 不超过500钻 否则就取小于105最大的
                            //取一个新礼物  替换后  用户超过100 不超过500钻 否则就取小于100最大的
                            for (Gift configGift : configGifts){
                                int incomeIfReplace = totalIncome + configGift.getCoin();
                                if (checkRate105(totalPay, incomeIfReplace) && checkRateLess105(totalPay, incomeIfReplace)){
                                    if (incomeIfReplace < (totalPay*1.0d + 500)) {
//                                        totalIncome = incomeIfReplace;
//                                    BeanUtils.copyProperties(configGift, gift);
                                        flag = true;
                                        PrizePatch prizePatch =  new PrizePatch();
                                        prizePatch.setGiftId(configGift.getId());
                                        prizePatch.setStep(0);
                                        prizePatch.setStatus("normal");
                                        prizePatch.setUserId(record.getUserId());
                                        prizePatch.setPrice(price);
                                        prizePatch.setCreateTime(new Date());
                                        prizePatchService.save(prizePatch);
                                        break;
                                    }
                                }else {
//                                    totalIncome = incomeIfReplace;
                                    while (!checkRate105(totalPay, incomeIfReplace)){
                                        flag = true;
                                        PrizePatch prizePatch =  new PrizePatch();
                                        prizePatch.setGiftId(configGift.getId());
                                        prizePatch.setStep(0);
                                        prizePatch.setStatus("normal");
                                        prizePatch.setUserId(record.getUserId());
                                        prizePatch.setPrice(price);
                                        prizePatch.setCreateTime(new Date());
                                        prizePatchService.save(prizePatch);
                                        totalIncome = totalIncome  + configGift.getCoin();
                                        incomeIfReplace = totalIncome;
                                        if (!checkRateLess105(totalPay, totalIncome)){
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (flag) {
                            ProtectGiftUser protectGiftUser = new ProtectGiftUser();
                            protectGiftUser.setUserId(record.getUserId());
                            protectGiftUser.setCreateTime(new Date());
                            protectGiftUserService.save(protectGiftUser);
                        }
                    }
                }

            }

        }

    }

    //是否大于105爆率
    private boolean checkRate105(int pay, int income) {
//        return BigDecimal.valueOf(income).divide(BigDecimal.valueOf(pay), 4, 2).doubleValue() > 1.05;
        return BigDecimal.valueOf(income).divide(BigDecimal.valueOf(pay), 4, 2).doubleValue() > 1.0;
    }

    private boolean checkRateLess105(int pay, int income) {
//        return BigDecimal.valueOf(income).divide(BigDecimal.valueOf(pay), 4, 2).doubleValue() > 1.05;
        return BigDecimal.valueOf(income).divide(BigDecimal.valueOf(pay), 4, 2).doubleValue() < 1.05;
    }

}
